package com.ruoyi.customer.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.domain.CsContract;
import com.ruoyi.customer.service.ICsContractService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * 合同管理Controller
 *
 * @author 李守壮
 * @date 2023-03-18
 */
@RestController
@RequestMapping("/customer/contract")
public class CsContractController extends BaseController {
    @Autowired
    private ICsContractService csContractService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询合同管理列表
     */
    @PreAuthorize("@ss.hasPermi('customer:contract:list')")
    @GetMapping("/list")
    public TableDataInfo list(CsContract csContract) {
        startPage();
        List<CsContract> list = csContractService.selectCsContractList(csContract);
        return getDataTable(list);
    }

    /**
     * 导出合同管理列表
     */
    @PreAuthorize("@ss.hasPermi('customer:contract:export')")
    @Log(title = "合同管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CsContract csContract) {
        List<CsContract> list = csContractService.selectCsContractList(csContract);
        ExcelUtil<CsContract> util = new ExcelUtil<CsContract>(CsContract.class);
        util.exportExcel(response, list, "合同管理数据");
    }

    /**
     * 获取合同管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('customer:contract:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(csContractService.selectCsContractById(id));
    }

    /**
     * 新增合同管理
     */
    @PreAuthorize("@ss.hasPermi('customer:contract:add')")
    @Log(title = "合同管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated CsContract csContract) {
        Date endDate = csContract.getContractEndDate();
        Date startDate = csContract.getContractStartDate();
        int compareTo = endDate.compareTo(startDate);
        if (-1 == compareTo){
            return error("结束时间不能早于开始时间");
        }
        return toAjax(csContractService.insertCsContract(csContract));
    }

    /**
     * 修改合同管理
     */
    @PreAuthorize("@ss.hasPermi('customer:contract:edit')")
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CsContract csContract) {
        return toAjax(csContractService.updateCsContract(csContract));
    }

    /**
     * 删除合同管理
     */
    @PreAuthorize("@ss.hasPermi('customer:contract:remove')")
    @Log(title = "合同管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(csContractService.deleteCsContractByIds(ids));
    }


    /**
     * 导入
     */
    @Log(title = "合同管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('customer:contract:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<CsContract> util = new ExcelUtil<CsContract>(CsContract.class);
        List<CsContract> list = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = csContractService.importData(list, updateSupport, operName);
        return success(message);
    }

    /**
     * 导出模版
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<CsContract> util = new ExcelUtil<CsContract>(CsContract.class);
        util.importTemplateExcel(response, "数据");
    }


    /**
     * 上传
     */
    @Log(title = "CsContract", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('customer:contract:fileUpload')")
    @PostMapping("/handleFileUpload")
    public AjaxResult fileUpload(MultipartFile file, String contractId) throws Exception {
        if (!file.isEmpty()) {
            String contractUrl = RuoYiConfig.getContractPath(contractId);
            String fileUrl = FileUploadUtils.upload(contractUrl, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            CsContract csContract = new CsContract();
            csContract.setId(Long.parseLong(contractId));
            csContract.setContractPicture(fileUrl);
            if (1 == csContractService.updateCsContract(csContract)) {
                StringBuilder successMsg = new StringBuilder();
                successMsg.append("合同上传成功！ 上传文件名称为 ： " + file.getName());
                return success(successMsg);
            }
        }
        return error("上传异常，请联系管理员");
    }




    /**
     * 下载
     */
    @PreAuthorize("@ss.hasPermi('customer:contract:fileExport')")
    @Log(title = "合同管理", businessType = BusinessType.EXPORT)
    @PostMapping("/fileExport")
    public void fileExport(HttpServletResponse response, HttpServletRequest request,CsContract csContract) {
        try {
            if (ObjectUtils.isEmpty(csContract) || ObjectUtils.isEmpty(csContract.getContractPicture())) { return; }
            String fileName = csContract.getContractPicture();
            String localPath = FileUploadUtils.getDefaultBaseDir();
            String downloadPath = localPath + StringUtils.substringAfter(fileName, Constants.RESOURCE_PREFIX);
            if (!FileUtils.checkAllowDownload(downloadPath)) { return; }//校验是否可下载
            // 下载名称
            String downloadName = FileUtils.getName(downloadPath);
//            FileUtils.setAttachmentResponseHeader(response, downloadName);

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
            FileUtils.writeBytes(downloadPath, response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
